const SegmentTree = require("../template")

function testSegmentTreeBasic() {
  const arr = [1, 3, 5, 7, 9, 11]
  const st = new SegmentTree(arr)

  console.log(
    "1. 基本区间查询测试:",
    (() => {
      return st.getRangeSum(0, 2) === 9 && // 1+3+5=9
             st.getRangeSum(1, 4) === 24 && // 3+5+7+9=24
             st.getRangeSum(0, 5) === 36 // 1+3+5+7+9+11=36
    })()
  )

  console.log(
    "2. 单点更新测试:",
    (() => {
      st.updateSingleValue(0, 10)
      return st.getSingleValue(0) === 10 &&
             st.getRangeSum(0, 2) === 18 // 10+3+5=18
    })()
  )

  console.log(
    "3. 区间更新测试:",
    (() => {
      st.updateRangeValue(1, 3, 2)
      return st.getRangeSum(1, 3) === 20 // (3+2)+(5+2)+(7+2)=20
    })()
  )

  console.log(
    "4. 单点查询测试:",
    (() => {
      return st.getSingleValue(0) === 10 &&
             st.getSingleValue(1) === 5 &&
             st.getSingleValue(2) === 7
    })()
  )

  console.log(
    "5. 边界查询测试:",
    (() => {
      return st.getRangeSum(0, 0) === 10 &&
             st.getRangeSum(5, 5) === 11 &&
             st.getRangeSum(0, 5) === 50
    })()
  )

  console.log(
    "6. this上下文线段树测试:",
    (() => {
      const stObj = {
        multiplier: 2,
        processSegmentTree: function(arr) {
          const st = new SegmentTree(arr)
          const sum = st.getRangeSum(0, arr.length - 1)
          return sum * this.multiplier
        }
      }
      return stObj.processSegmentTree([1, 2, 3]) === 12 // (1+2+3)*2=12
    })()
  )

  console.log(
    "7. 复杂对象this绑定线段树测试:",
    (() => {
      const stConfigObj = {
        config: { offset: 5 },
        processWithConfig: function(arr) {
          const st = new SegmentTree(arr)
          const sum = st.getRangeSum(0, arr.length - 1)
          return sum + this.config.offset
        }
      }
      return stConfigObj.processWithConfig([1, 2, 3]) === 11 // (1+2+3)+5=11
    })()
  )

  console.log(
    "8. 线段树一致性测试:",
    (() => {
      const consistencySt = new SegmentTree([1, 2, 3, 4, 5])
      const sum1 = consistencySt.getRangeSum(0, 4)
      consistencySt.updateSingleValue(0, 10)
      const sum2 = consistencySt.getRangeSum(0, 4)
      return sum1 === 15 && sum2 === 24
    })()
  )

  console.log(
    "9. 线段树边界测试:",
    (() => {
      const boundarySt = new SegmentTree([1])
      return boundarySt.getRangeSum(0, 0) === 1 &&
             boundarySt.getSingleValue(0) === 1
    })()
  )

  console.log(
    "10. 线段树性能测试:",
    (() => {
      const largeArr = Array.from({ length: 1000 }, (_, i) => i + 1)
      const perfSt = new SegmentTree(largeArr)
      const start = performance.now()
      perfSt.getRangeSum(0, 999)
      perfSt.updateRangeValue(0, 999, 1)
      const end = performance.now()
      return (end - start) < 1000
    })()
  )
}

testSegmentTreeBasic()
